package com.btl.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.btl.bean.ZuiXin;
import com.btl.cygf.FenleiActivity;
import com.btl.cygf.R;
import com.btl.cygf.SousuoActivity;
import com.btl.cygf.ZhuanJiActivity;
import com.btl.ui.adapter.ViewPaperAdapter;
import com.btl.utils.DownTuUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ShouyeFragment extends Fragment implements View.OnClickListener,Runnable{
	
	
	//LinearLayout布局
	private LinearLayout Checkin_search,zhiyi,suliao,jiaju,zixun,diy,jinshu,lipin,muzhi;
	//图片轮播的布局
	private ViewPager viewPager;
	private ViewGroup group;
    private ViewPaperAdapter mAdapter;
    private List<View> mViewPicture;
    private ImageView[] mImageViews = null;
    private ImageView imageView = null;
    private AtomicInteger what = new AtomicInteger(0);
    private boolean isContinue = true;
    private AsyncHttpClient client;
	private RequestParams params;
	private FrameLayout shougong;
	private ImageView zhuanjipic;
	private TextView zhuanjimingzi;
	private TextView zhuanjijieshao;
	private LinearLayout zhuanji;
	private ZuiXin zuiXin;
	
	
	private String z_id;   //专辑 的  id
    
    private final Handler viewHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			viewPager.setCurrentItem(msg.what);
			super.handleMessage(msg);
		}
    	
    };

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View messageLayout = inflater.inflate(R.layout.shouye_layout,
				container, false);
		Checkin_search=(LinearLayout) messageLayout.findViewById(R.id.Checkin_search);
		zhiyi=(LinearLayout) messageLayout.findViewById(R.id.zhiyi);
		suliao=(LinearLayout) messageLayout.findViewById(R.id.suliao);
		jiaju=(LinearLayout) messageLayout.findViewById(R.id.jiaju);
		zixun=(LinearLayout) messageLayout.findViewById(R.id.boli);
		diy=(LinearLayout) messageLayout.findViewById(R.id.diy);
		jinshu=(LinearLayout) messageLayout.findViewById(R.id.jinshu);
		lipin=(LinearLayout) messageLayout.findViewById(R.id.lipin);
		muzhi=(LinearLayout) messageLayout.findViewById(R.id.muzhi);
		
	
		shougong = (FrameLayout) messageLayout.findViewById(R.id.shougong);
		
		
		shougong.setOnClickListener(this);
		
		
		Checkin_search.setOnClickListener(this);
		zhiyi.setOnClickListener(this);
		suliao.setOnClickListener(this);
		jiaju.setOnClickListener(this);
		zixun.setOnClickListener(this);
		diy.setOnClickListener(this);
		jinshu.setOnClickListener(this);
		lipin.setOnClickListener(this);
		muzhi.setOnClickListener(this);
		
		
		return messageLayout;
		
		
	}
	
	

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		zhuanjipic= (ImageView) getActivity().findViewById(R.id.zhuanjipic);
		zhuanjimingzi=(TextView) getActivity().findViewById(R.id.zhuanjimingzi);
		zhuanjijieshao=(TextView) getActivity().findViewById(R.id.zhuanjijieshao);
		client = new AsyncHttpClient();
		// 像网络传输的数据
		params = new RequestParams();
		// 链接到网络，获取数据
		getDataRefresh();
	}



	private void getDataRefresh() {
		client.post(getResources().getString(R.string.url) + "/CYGF/ZhuanJi",new JsonHttpResponseHandler() {
					// 链接成功做出的反应
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONArray response) {
						zuiXin = new ZuiXin();
						JSONObject object = response.optJSONObject(0);
						String s1 = object.optString("z_name");
						String s2 = object.optString("z_jieshao");
						String  s3 = object.optString("z_image");
						String s4 = object.optString("z_id");
						z_id = s4;
						zhuanjimingzi.setText(s1);
						zhuanjijieshao.setText(s2);
						zuiXin.setPicture(s3);
						ImageLoader imageLoader = ImageLoader.getInstance();
						imageLoader.init(DownTuUtils.getConfig(getActivity()));
						imageLoader.displayImage(s3 , zhuanjipic, DownTuUtils.getOptions());
						
					}	
					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						super.onFailure(statusCode, headers, responseString, throwable);
					}
					// 链接网络失败，做出的反应
					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONArray errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
						
					}
				});
	}



	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		viewPager=(ViewPager) view.findViewById(R.id.viewpager);
		group=(ViewGroup) view.findViewById(R.id.viewGroup);
		
		mViewPicture=new ArrayList<View>();
		ImageView img1 = new ImageView(getActivity());
        img1.setBackgroundResource(R.drawable.advertising_default_1);
        mViewPicture.add(img1);
        
        ImageView img2 = new ImageView(getActivity());
        img2.setBackgroundResource(R.drawable.advertising_default_2);
        mViewPicture.add(img2);

        ImageView img3 = new ImageView(getActivity());
        img3.setBackgroundResource(R.drawable.advertising_default_3);
        mViewPicture.add(img3);

        ImageView img4 = new ImageView(getActivity());
        img4.setBackgroundResource(R.drawable.advertising_default_4);
        mViewPicture.add(img4);
        
        mImageViews = new ImageView[mViewPicture.size()];
        
        for (int i = 0; i < mViewPicture.size(); i++) {
        	imageView = new ImageView(getActivity());
            imageView.setLayoutParams(new LayoutParams(20, 20));
            imageView.setPadding(5, 5, 5, 5);
            mImageViews[i] = imageView;
            if (i == 0) {
                mImageViews[i].setBackgroundResource(R.drawable.ic_viewpager_select);
            } else {
                mImageViews[i].setBackgroundResource(R.drawable.ic_viewpager_noselect);
            }
            group.addView(mImageViews[i]);
		}
        viewPager.setOnPageChangeListener(new GuidePageChangeListener());
        mAdapter = new ViewPaperAdapter(mViewPicture);
        viewPager.setAdapter(mAdapter);
        viewPager.setOnTouchListener(new GuideOnTouchListener());
        new Thread(this).start();
		
	}
	
	 private final class GuidePageChangeListener implements OnPageChangeListener {

	        @Override
	        public void onPageScrollStateChanged(int arg0) {

	        }
	        @Override
	        public void onPageScrolled(int arg0, float arg1, int arg2) {

	        }

	        @Override
	        public void onPageSelected(int arg0) {
	            what.getAndSet(arg0);
	            for (int i = 0; i < mImageViews.length; i++) {
	                mImageViews[arg0].setBackgroundResource(R.drawable.ic_viewpager_select);
	                if (arg0 != i) {
	                    mImageViews[i].setBackgroundResource(R.drawable.ic_viewpager_noselect);
	                }
	            }
	        }
	    }
	 
	 private final class GuideOnTouchListener implements OnTouchListener{

	        /* (non-Javadoc)
	         * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
	         */
	        @Override
	        public boolean onTouch(View v, MotionEvent event) {
	            switch (event.getAction()) {
	                case MotionEvent.ACTION_DOWN:
	                case MotionEvent.ACTION_MOVE:
	                    isContinue = false;
	                    break;
	                case MotionEvent.ACTION_UP:
	                    isContinue = true;
	                    break;
	                default:
	                    isContinue = true;
	                    break;
	            }
	            return false;
	        }

	    }
	 
	  private void whatOption() {
	        what.incrementAndGet();
	        if (what.get() > mImageViews.length - 1) {
	            what.getAndAdd(-4);
	        }
	        try {
	            Thread.sleep(5000);
	        } catch (InterruptedException e) {

	        }
	    }
	    /* (non-Javadoc)
	     * @see java.lang.Runnable#run()
	     */
	  
	  
	    @Override
	    public void run() {
	        while (true) {
	            if (isContinue) {
	                viewHandler.sendEmptyMessage(what.get());
	                whatOption();
	            }
	        }
	    }



	private void initView(View view) {
		Checkin_search=(LinearLayout) view.findViewById(R.id.Checkin_search);
		zhiyi=(LinearLayout) view.findViewById(R.id.zhiyi);
		suliao=(LinearLayout) view.findViewById(R.id.suliao);
		jiaju=(LinearLayout) view.findViewById(R.id.jiaju);
		zixun=(LinearLayout) view.findViewById(R.id.boli);
		diy=(LinearLayout) view.findViewById(R.id.diy);
		jinshu=(LinearLayout) view.findViewById(R.id.jinshu);
		lipin=(LinearLayout) view.findViewById(R.id.lipin);
		muzhi=(LinearLayout) view.findViewById(R.id.muzhi);
		
		
		shougong = (FrameLayout) view.findViewById(R.id.shougong);
		
		zhuanji=(LinearLayout) getActivity().findViewById(R.id.zhuanji);
		
		
		shougong.setOnClickListener(this);
		
		Checkin_search.setOnClickListener(this);
		zhiyi.setOnClickListener(this);
		suliao.setOnClickListener(this);
		jiaju.setOnClickListener(this);
		zixun.setOnClickListener(this);
		diy.setOnClickListener(this);
		jinshu.setOnClickListener(this);
		lipin.setOnClickListener(this);
		muzhi.setOnClickListener(this);
		zhuanji.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		Bundle bundle=new Bundle();
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.Checkin_search:
			//点击跳转
			intent.setClass(getActivity(), SousuoActivity.class);
			startActivity(intent);
			break;
		case R.id.zhiyi:
			//点击跳转
			bundle.putString("title","纸艺");
			intent.putExtras(bundle);
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.suliao:
			//点击跳转
			intent.putExtra("title","塑料");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.jiaju:
			//点击跳转
			intent.putExtra("title","家居");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.boli:
			//点击跳转
			intent.putExtra("title","玻璃");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.diy:
			//点击跳转
			intent.putExtra("title","DIY");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.jinshu:
			//点击跳转
			intent.putExtra("title","金属");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.lipin:
			//点击跳转
			intent.putExtra("title","礼品");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.muzhi:
			//点击跳转
			intent.putExtra("title","木制");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		
			
		case R.id.shougong:
			intent.putExtra("title","传统手工");
			intent.setClass(getActivity(), FenleiActivity.class);
			startActivity(intent);
			break;
		case R.id.zhuanji:
			intent.putExtra("z_id", z_id);
			intent.putExtra("zhuanjitouming", zhuanjimingzi.getText());
			intent.putExtra("zhuanjitoujianjie", zhuanjijieshao.getText());
			intent.putExtra("zhuanjitoupic",zuiXin.getPicture() );
			intent.setClass(getActivity(), ZhuanJiActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		
	}

}
